package com.novabluetooth.services.bluetooth2;

import java.io.IOException;
import java.util.UUID;

import com.novabluetooth.services.BluetoothConstant;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class BluetoothChatService {

	private static final String TAG = "BluetoothChatService";
	private static final boolean D = true;

	private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

	private BluetoothAdapter mAdapter;
	private Handler mHandler;

	private AcceptThread mAcceptThread;
	Context context;

	private int mState;
	public static final int STATE_NONE = 0;
	public static final int STATE_LISTEN = 1;
	public static final int STATE_CONNECTING = 2;
	public static final int STATE_CONNECTED = 3;

	public BluetoothChatService(Context context, Handler handler) {
		this.context=context;
		mAdapter = BluetoothAdapter.getDefaultAdapter();
		mState = STATE_NONE;
		mHandler = handler;
	}

	public synchronized int getState() {
		return mState;
	}

	private synchronized void setState(int state) {

		mState = state;
		mHandler.obtainMessage(MessageValue.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
	}

	public synchronized void start() {

		if (D)
			Log.d(TAG, "Bluetooth service start");
		setState(STATE_LISTEN);

		if (mAcceptThread == null) {
			mAcceptThread = new AcceptThread();
			mAcceptThread.start();
		}

	}

	public synchronized void stop() {

		if (D)
			Log.d(TAG, "stop");

		if (mAcceptThread != null) {
			mAcceptThread.cancel();
			mAcceptThread = null;
		}
		setState(STATE_NONE);
	}

	private class AcceptThread extends Thread {

		private BluetoothServerSocket mmServerSocket;
		BluetoothSocket socket;

		public AcceptThread() {
			BluetoothServerSocket tmp = null;
			try {
				tmp = mAdapter.listenUsingRfcommWithServiceRecord("BluetoothChat", SPP_UUID);
			} catch (IOException e) {
				Log.e(TAG, "AcceptThread()初始化发生异常,信息为" + e.getMessage());
			}
			mmServerSocket = tmp;
		}

		@Override
		public void run() {
			if (D)
				Log.d(TAG, "BEGIN mAcceptThread" + this);

			try {
				Log.i(TAG, getName() + "  Listening...");
				if (mmServerSocket != null) {

					socket = mmServerSocket.accept();

					Log.i(TAG, "===Have a Connect, Accept()");
					Log.i(TAG, "===This Remote Device Name:  " + socket.getRemoteDevice().getName() + "  Address:  "
							+ socket.getRemoteDevice().getAddress());

					synchronized (BluetoothChatService.this) {

						if (socket != null) {

							if (!selectDevice(socket)) {
								BluetoothChatService.this.connectionLost();
							}
						}
					}
				} else {
					Log.e(TAG, "mmServerSocket为空，无法开启蓝牙！");
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			} catch (IOException e) {
				Log.e(TAG, "AcceptThread.run()发生异常,信息为" + e.getMessage());
			}

		}

		public void cancel() {
			if (D)
				Log.d(TAG, "Socket cancel " + this);
			mState = STATE_CONNECTED;
			try {
				if (mmServerSocket != null) {
					mmServerSocket.close();
					mmServerSocket = null;
				}
				if (socket != null) {
					socket.close();
					socket = null;
				}
			} catch (IOException e) {
				Log.e(TAG, "AcceptThread.cancel()发生异常,信息为" + e.getMessage());
			}
		}
	}

	private boolean selectDevice(BluetoothSocket bluetoothSocket) {
		String btDeviceName = null;
		boolean isExist = false;
		if (bluetoothSocket != null) {
			btDeviceName = bluetoothSocket.getRemoteDevice().getName();
			Log.i(TAG, "获取到的蓝牙外围设备名称：    " + btDeviceName);
			if (btDeviceName != null) {
				// if (btDeviceName.equals("NOVABT")) { // 检测到血氧仪测量数据的处理
				// new BTThread(bluetoothSocket, mHandler).start();
				// isExist = true;
				// } else
				// if (btDeviceName.equals("NOVABG")) { // 检测到血糖仪测量数据的处理
				// new HBThread(bluetoothSocket, mHandler).start();
				// isExist = true;

				if (BluetoothConstant.TIWEN_HTD2.equals(btDeviceName)) { // 检测到血糖仪测量数据的处理
					Intent intent=new Intent();
					intent.setAction(BluetoothConstant.REGISTER_Waiting);
					context.sendBroadcast(intent);
					new HTDEWQ2Thread(bluetoothSocket, mHandler).start();
					isExist = true;
				} 
//				else if (btDeviceName.equals("NOVABG")) { // 检测到血糖仪测量数据的处理
//					new HBThread(bluetoothSocket, mHandler).start();
//					isExist = true;
//				}
				// else if (btDeviceName.equals("NOVATF")) { // 检测到体温计测量数据的处理
				// new TFThread(bluetoothSocket, mHandler).start();
				// isExist = true;
				// } else if (btDeviceName.equals("NOVAPA")) { // 检测到体温计测量数据的处理
				// new PAThread(bluetoothSocket, mHandler).start();
				// isExist = true;
				// } else if (btDeviceName.equals("NOVABU")) { // 检测到尿机测量数据的处理
				// new BUThread(bluetoothSocket, mHandler).start();
				// isExist = true;
				// }else if (btDeviceName.equals("NOVABW")) { // 检测到体重计测量数据的处理
				// new TZThread(bluetoothSocket, mHandler).start();
				// isExist = true;
				// } else if (btDeviceName.equals("NOVAUR")) { // 检测到体重计测量数据的处理
				// new NJThread(bluetoothSocket, mHandler).start();
				// isExist = true;
				// }else {
				// Log.i(TAG, "获取到的蓝牙外围设备不属于3G健康通");
				// isExist = false;
				// }
			}
		}
		return isExist;
	}

	public void connectionLost() {

		Message msg = mHandler.obtainMessage(MessageValue.MESSAGE_TOAST);
		Bundle bundle = new Bundle();
		bundle.putString("ToastValue", "蓝牙设备连接断开");
		msg.setData(bundle);
		mHandler.sendMessage(msg);

		BluetoothChatService.this.start();
		Log.i(TAG, "重新启动蓝牙接口...");
	}
}
